﻿import 'package:bot_toast/bot_toast.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:simu_studio/app/modules/home/controllers/home_controller.dart';
import 'package:simu_studio/app/pages/page_mixin.dart';
import 'package:simu_studio/app/services/mqtt_client_service.dart';

class HomeSettingView extends StatelessWidget with PageMixin {
  final TextEditingController mqttServerIPController = TextEditingController();
  final TextEditingController mqttServerPortController =
      TextEditingController();
  final TextEditingController mqttSubscribeChannelController =
      TextEditingController();

  final TextEditingController influxDBServerIPController =
      TextEditingController();
  final TextEditingController influxDBServerPortController =
      TextEditingController();
  final TextEditingController influxDBOrgController = TextEditingController();
  final TextEditingController influxDBBucketController =
      TextEditingController();
  final TextEditingController influxDBTokenController = TextEditingController();
  final TextEditingController influxDBBatchSizeController =
      TextEditingController();

  @override
  Widget build(BuildContext context) {
    const spacer = SizedBox(height: 10);
    const bigspacer = SizedBox(height: 40);
    _initTextControllers();
    HomeController controller = Get.find();
    return ScaffoldPage.scrollable(
      padding: const EdgeInsets.all(10),
      header: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Text(
          'Settings'.tr,
          style: const TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
        ),
      ),
      children: [
        subtitle(content: Text('Home_MqttSettings'.tr)),
        Card(
            child: Column(
          children: [
            InfoLabel(
              label: "Home_MqttServerIP".tr,
              child: TextBox(
                controller: mqttServerIPController,
              ),
            ),
            // spacer,
            // InfoLabel(
            //   label: "Home_MqttServerPort".tr,
            //   child: TextBox(
            //     controller: mqttServerPortController,
            //   ),
            // ),
            spacer,
            InfoLabel(
              label: "Home_MqttSubscribeChannel".tr,
              child: TextBox(
                controller: mqttSubscribeChannelController,
              ),
            )
          ],
        )),
        subtitle(content: Text('Home_InfluxDBSettings'.tr)),
        Card(
          child: Column(children: [
            InfoLabel(
              label: "Home_InfluxDBServerIP".tr,
              child: TextBox(
                controller: influxDBServerIPController,
              ),
            ),
            spacer,
            InfoLabel(
              label: "Home_InfluxDBServerPort".tr,
              child: TextBox(
                controller: influxDBServerPortController,
              ),
            ),
            spacer,
            InfoLabel(
              label: "Home_InfluxDBServerOrg".tr,
              child: TextBox(
                controller: influxDBOrgController,
              ),
            ),
            spacer,
            InfoLabel(
              label: "Home_InfluxDBServerBucket".tr,
              child: TextBox(
                controller: influxDBBucketController,
              ),
            ),
            spacer,
            InfoLabel(
              label: "Home_InfluxDBServerToken".tr,
              child: TextBox(
                controller: influxDBTokenController,
                placeholder: 'Home_InfluxDBServerTokenPlaceHolder'.tr,
              ),
            ),
            spacer,
            InfoLabel(
              label: "Home_InfluxDBBatchSize".tr,
              child: TextBox(
                controller: influxDBBatchSizeController,
                placeholder: 'Home_InfluxDBBatchSizePlaceHolder'.tr,
              ),
            )
          ]),
        ),
        bigspacer,
        Row(
          children: [
            const Spacer(),
            Obx(
              () => FilledButton(
                onPressed: !controller.verifyStatus.value ? _onVerify : null,
                child: Text('Home_Buttons_Verify'.tr),
              ),
            ),
          ],
        )
      ],
    );
  }

  void _onVerify() async {
    MqttClientService clientService = Get.find();
    if (clientService.isConnected()) {
      return;
    }
    HomeController controller = Get.find();
    if (mqttServerIPController.text.trim().isEmpty) {
      infomationMessage('Home_Toast_MqttServerIPIsEmpty'.tr);
      return;
    }
    if (mqttServerPortController.text.trim().isEmpty) {
      infomationMessage('Home_Toast_MqttServerPortIsEmpty'.tr);
      return;
    }
    if (mqttSubscribeChannelController.text.trim().isEmpty) {
      infomationMessage('Home_Toast_MqttServerSubscribeChannelIsEmpty');
      return;
    }
    if (influxDBServerIPController.text.trim().isEmpty) {
      infomationMessage('Home_Toast_InfluxDBServerIPIsEmpty'.tr);
      return;
    }
    if (influxDBServerPortController.text.trim().isEmpty) {
      infomationMessage('Home_Toast_InfluxDBServerPortIsEmpty'.tr);
      return;
    }
    if (influxDBOrgController.text.trim().isEmpty) {
      infomationMessage('Home_Toast_InfluxDBServerOrgIsEmpty'.tr);
      return;
    }
    if (influxDBBucketController.text.trim().isEmpty) {
      infomationMessage('Home_Toast_InfluxDBServerBucketIsEmpty'.tr);
      return;
    }
    if (influxDBTokenController.text.trim().isEmpty) {
      infomationMessage('Home_Toast_InfluxDBServerTokenIsEmpty'.tr);
      return;
    }
    if (influxDBBatchSizeController.text.trim().isEmpty) {
      infomationMessage('Home_Toast_InfluxDBBatchSizeIsEmpty'.tr);
      return;
    }
    controller.mqConfig.serverIP = mqttServerIPController.text.trim();
    controller.mqConfig.serverPort =
        int.parse(mqttServerPortController.text.trim());
    controller.mqConfig.subscriptions =
        mqttSubscribeChannelController.text.trim();
    controller.mqConfig.saveToStorage();

    controller.dbConfig.serverIP = influxDBServerIPController.text.trim();
    controller.dbConfig.port =
        int.parse(influxDBServerPortController.text.trim());
    controller.dbConfig.organizationName = influxDBOrgController.text.trim();
    controller.dbConfig.bucket = influxDBBucketController.text.trim();
    controller.dbConfig.token = influxDBTokenController.text.trim();
    controller.dbConfig.batchSize =
        int.parse(influxDBBatchSizeController.text.trim());
    controller.dbConfig.saveToStorage();

    bool succeed = await controller.connectToMQ();
    if (!succeed) {
      infomationMessage('Home_Toast_MqttConnectFailed'.tr);
      return ;
    }
    succeed = controller.connectToDB();
    if(!succeed){
      infomationMessage('Home_Toast_DBConnectedFailed'.tr);
      return ;
    }
    infomationMessage('Home_Toast_EnvironmentVerifySucceed'.tr);
  }

  void _initTextControllers() {
    HomeController controller = Get.find();
    mqttServerIPController.text = controller.mqConfig.serverIP;
    mqttServerPortController.text = controller.mqConfig.serverPort.toString();
    mqttSubscribeChannelController.text = controller.mqConfig.subscriptions;

    influxDBServerIPController.text = controller.dbConfig.serverIP;
    influxDBServerPortController.text = controller.dbConfig.port.toString();
    influxDBOrgController.text = controller.dbConfig.organizationName;
    influxDBBucketController.text = controller.dbConfig.bucket;
    influxDBTokenController.text = controller.dbConfig.token;
    influxDBBatchSizeController.text = controller.dbConfig.batchSize.toString();
  }
}
